package util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Tag {
	private String type;
	private Properties prop;
	private List<Tag> childTags;
	private String content;

	public Tag() {

	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Properties getProp() {
		return prop;
	}

	public void setProp(Properties prop) {
		this.prop = prop;
	}

	public List<Tag> getchildTags() {
		return childTags;
	}

	public void setchildTags(List<Tag> childTags) {
		this.childTags = childTags;
	}

	public void addChildTag(Tag tag) {
		if (childTags == null)
			childTags = new ArrayList<Tag>();
		this.childTags.add(tag);
	}

	public static Tag makeTag(Element e) {
		Tag tag = new Tag();
		tag.setType(e.getTagName());
		Properties prop = new Properties();

		NamedNodeMap attris = e.getAttributes();
		for (int j = 0; j < attris.getLength(); ++j) {
			Node attri = attris.item(j);
			prop.setProperty(attri.getNodeName(), attri.getNodeValue());
		}
		tag.setProp(prop);

		NodeList childTags = e.getChildNodes();
		for (int j = 0; j < childTags.getLength(); ++j) {
			Node n = childTags.item(j);
			if (n.getNodeType() == Node.ELEMENT_NODE) {
				Element childTag = (Element) n;
				tag.addChildTag(makeTag(childTag));
			} else if (n.getNodeType() == Node.TEXT_NODE) {
				tag.setContent(n.getTextContent());
			}
		}
		return tag;
	}

	public void getRecurTag(Element e) {

	}

	public static List<Tag> makeTagForBeanProperty(Properties prop) {
		List<Tag> propertyTags = new ArrayList<Tag>();

		if (prop != null) {
			Enumeration<Object> keys = prop.keys();

			while (keys.hasMoreElements()) {
				Tag tag = new Tag();
				tag.setType("beans:property");

				String obj = (String) keys.nextElement();
				String value = prop.getProperty(obj);

				Properties attrProp = new Properties();
				attrProp.setProperty("name", obj);
				attrProp.setProperty("value", value);

				tag.setProp(attrProp);
				propertyTags.add(tag);
			}

		}

		return propertyTags;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
}
